package demo.spring.framework.web.bind;

import java.beans.PropertyEditorSupport;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringEscapeUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class WebDataBinderDemo {

    private static Logger logger = LoggerFactory.getLogger(WebDataBinderDemo.class);

    /**
     * 参数绑定异常
     * 
     * @ExceptionHandler({ BindException.class, ConstraintViolationException.class,
     *                     ValidationException.class }) public String bindException() { return
     *                     "error/400"; }
     */

    /**
     * 初始化数据绑定 1. 将所有传递进来的String进行HTML编码，防止XSS攻击 2. 将字段中Date类型转换为String类型
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }

            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
    }

    @Test
    public void test() throws UnsupportedEncodingException {
        String input = "<h1>http://Stan@126.com</h1>";
        String output = StringEscapeUtils.escapeHtml4(input);
        String encodedStr = URLEncoder.encode(input, "UTF-8");
        logger.info(" StringEscapeUtils.escapeHtml4({}) = {} ", input, output);
        logger.info(" URLEncoder.encode({}) = {} ", input, encodedStr);
    }

    protected HttpServletRequest currentRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    protected HttpSession currentSession() {
        return currentRequest().getSession();
    }

}
